<template>
  <div class="goods-service">
    <el-row :gutter="20">
      <el-col :span="8" v-for="goods in goodsList" :key="goods.goodsId">
        <el-card class="goods-card">
          <div class="goods-image">
            <img :src="getGoodsImage(goods)" :alt="goods.goodsName" @error="handleImageError" />
          </div>
          <div class="goods-info">
            <h3>{{ goods.goodsName }}</h3>
            <p class="description">{{ goods.goodsDesc }}</p>
            <div class="goods-tags">
              <el-tag v-for="tag in goods.tags" :key="tag" size="small" style="margin-right: 5px;">
                {{ tag }}
              </el-tag>
            </div>
            <div class="price-info">
              <span class="price">¥{{ goods.goodsPrice }}</span>
              <span class="original-price" v-if="goods.originalPrice">¥{{ goods.originalPrice }}</span>
            </div>
            <div class="credit-info">
              <el-tag :type="canPurchase(goods) ? 'success' : 'warning'" size="small">
                {{ getCreditTagText(goods) }}
              </el-tag>
            </div>
          </div>
          <div class="goods-actions">
            <el-button
              type="primary"
              size="small"
              @click="viewDetail(goods)"
              style="margin-right: 10px;">
              查看详情
            </el-button>
            <el-button
              :type="canPurchase(goods) ? 'success' : 'info'"
              size="small"
              @click="buyGoods(goods)"
              :disabled="!canPurchase(goods)">
              {{ getPurchaseButtonText(goods) }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 暂无数据 -->
    <div v-if="goodsList.length === 0" class="no-data">
      <el-empty description="暂无商品信息"></el-empty>
    </div>
  </div>
</template>

<script>
import { listGoods, buyGoods } from '@/api/credit/businessService'

export default {
  name: "GoodsService",
  props: {
    userScore: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      goodsList: [],
      loading: false
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    /** 获取商品列表 */
    getGoodsList() {
      this.loading = true;
      listGoods().then(response => {
        if (response.code === 200) {
          this.goodsList = response.data || [];
          // 确保recommendScore是数字类型
          this.goodsList.forEach(item => {
            item.recommendScore = Number(item.recommendScore) || 0;
          });
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 检查是否可以购买 */
    canPurchase(goods) {
      const userScore = Number(this.userScore) || 0;
      const recommendScore = Number(goods.recommendScore) || 0;
      return userScore >= recommendScore;
    },

    /** 获取信用标签文本 */
    getCreditTagText(goods) {
      return this.canPurchase(goods) ? '可享优惠' : `需要${goods.recommendScore}分`;
    },

    /** 获取购买按钮文本 */
    getPurchaseButtonText(goods) {
      return this.canPurchase(goods) ? '优惠购买' : '信用分不足';
    },

    /** 查看商品详情 */
    viewDetail(goods) {
      this.$alert(`
        <div style="text-align: left;">
          <h3>${goods.goodsName}</h3>
          <p><strong>分类：</strong>${goods.goodsCategory}</p>
          <p><strong>价格：</strong>¥${goods.goodsPrice}</p>
          <p><strong>推荐信用分：</strong>${goods.recommendScore}分</p>
          <p><strong>库存：</strong>${goods.stockQuantity || 0}件</p>
          <p><strong>描述：</strong>${goods.goodsDesc || '暂无详细描述'}</p>
        </div>
      `, '商品详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        customClass: 'goods-detail-dialog'
      });
    },

    /** 获取商品图片 */
    getGoodsImage(goods) {
      if (goods.goodsImages) {
        try {
          const images = JSON.parse(goods.goodsImages);
          if (images && images.length > 0) {
            return this.getImageUrl(images[0]);
          }
        } catch (e) {
          console.warn('解析商品图片失败:', e);
        }
      }
      return '';
    },

    /** 处理图片加载错误 */
    handleImageError(event) {
      event.target.src = '';
    },

    /** 获取图片完整URL */
    getImageUrl(imagePath) {
      if (!imagePath) return '';
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath;
      }
      return process.env.VUE_APP_BASE_API + imagePath;
    },

    /** 购买商品 */
    buyGoods(goods) {
      if (!this.canPurchase(goods)) {
        this.$message.warning(`您的信用分不足，需要${goods.recommendScore}分才能享受此优惠`);
        return;
      }
      this.$confirm(`确认购买"${goods.goodsName}"？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const buyData = {
          goodsId: goods.goodsId,
          quantity: 1,
          paymentMethod: "installment"
        };
        buyGoods(buyData).then(response => {
          if (response.code === 200) {
            this.$message.success(response.data.message || "商品购买成功");
          } else {
            this.$message.error(response.msg || "商品购买失败");
          }
        }).catch(() => {
          this.$message.error("商品购买失败，请稍后重试");
        });
      });
    }
  }
};
</script>

<style scoped>
.goods-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.goods-card:hover {
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}

.goods-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 15px;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.description {
  color: #909399;
  font-size: 12px;
  margin-bottom: 10px;
}

.goods-tags {
  margin-bottom: 10px;
}

.price-info {
  margin-bottom: 10px;
}

.price {
  color: #E6A23C;
  font-size: 20px;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  color: #C0C4CC;
  font-size: 14px;
  text-decoration: line-through;
}

.credit-info {
  margin-bottom: 15px;
}

.goods-actions {
  text-align: center;
}

.no-data {
  text-align: center;
  padding: 60px 0;
}
</style>
